package xyz.csmcool.imserver.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import xyz.csmcool.imutil.webVo.RedisService;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 什锦
 * @Package xyz.csmcool.imchat.config
 * @since 2022/8/14 14:11
 */
@Component
@Slf4j
public class HttpAuthHandler extends TextWebSocketHandler {

    @Autowired
    RedisService redisService;

    /**
     * socket 建立成功事件
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Object uid = session.getAttributes().get("uid");
        Object roomId = session.getAttributes().get("roomId");
        if (uid != null) {
            // 用户连接成功，放入在线用户缓存
            WsSessionManager.add((Integer) uid, (Integer) roomId, session);
        } else {
            throw new RuntimeException("用户登录已经失效!");
        }
    }
    /**
     * 接收消息事件
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 获得客户端传来的消息
        String payload = message.getPayload();
        Object uid = session.getAttributes().get("uid");
        System.out.println("server 接收到 " + uid + " 发送的 " + payload);
        session.sendMessage(new TextMessage("server 发送给 " + uid + " 消息 " + payload + " " +    LocalDateTime.now().toString()));
    }

    /**
     * socket 断开连接时
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object uid = session.getAttributes().get("uid");
        Object roomId = session.getAttributes().get("roomId");
        if (uid != null) {
            // 用户退出，移除缓存
            WsSessionManager.remove((Integer) uid, (Integer) roomId);
        }
    }

    public static void onMessage(String message,Integer roomId) {
        if(StringUtils.isNotBlank(message)){
            Map<Integer, WebSocketSession> users = WsSessionManager.get(roomId);
            if(roomId != null&& users != null){
                for (WebSocketSession session : users.values()) {
                    try {
                        session.sendMessage(new TextMessage(message));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
